class ImagesController < ApplicationController

# Begin authentication
  attr_reader :actions_to_check
  def initialize
    @actions_to_check = {:destroy => ['owner'],
                         :edit => ['owner'],
                         :show => ['owner', 'private'],
                         :update_ajax => ['owner'],
                         :tag => ['owner']}
  end

  def tag_owner_authorise params
    @result = Image.find(:all, :conditions => [ "id IN (?) AND user_id <> 4", params[:selected_ids].split(',') ])
    puts @result.size
    if @result.size > 0
      return false
    else
      return true
    end
  end

# End
  def index
    redirect_to :controller => :groups, :action => :list
  end

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :controller => :groups,:action => :list }

#  def list
#    if params[:group_id]!=nil   #list all images of the group
#        @image_pages, @images = paginate :images, :conditions => ["group_id = ?", params[:group_id]], :per_page => 18
#        @group = Group.find_by_id(params[:group_id])
#    else
#        flash[:notice] = "Please choose the image group you would like to view."
#        redirect_to :controller => :groups, :action => :list
#    end
#
#    if request.xhr?
#      render :partial => 'images'
#    end
#  end

  #This is the controller of the tag_list of the images of the current user.
  def tag_list
     @image_pages, @images = paginate :images, :conditions => ["user_id = ? and tags.id = ?", Goldberg.user.id, params[:id]], :include => [:tags], :per_page => 18
     @tag = @images[0].tags
     render :action => 'list'
  end

  def slideshow
    #puts params.inspect
    if (params[:selected_ids])
      @images = Image.find(:all, :conditions => {:id => params[:selected_ids].split(',')})
      render :layout => false
    else
      flash[:error] = 'You should choose some images before starting the slideshow';
    end
  end

  def show
    @image = Image.find(params[:id])
    @tags = @image.tags.collect {|t| t.name}
  end

  def new
    @image = Image.new
    @group_id =params[:group_id]
    puts params[:group_id]
    @user_groups = Group.find(:all, :conditions => ["users.id = ?", Goldberg.user.id], :include => [:user])
  end

  def create
      if(params[:group][:id]!=nil)
        if params[:group][:id] == "New Group"
            group = Group.new({:user_id=> Goldberg.user.id, :name => params[:group][:name]})
            group.save
            group_id = group.id
        else
            group_id =params[:group][:id]
        end

      end
#      puts params.inspect
      @images = []
      params['picture_files'].each do |file|
        next if file.class == String #empty input
        image_params = {:user_id => Goldberg.user.id, #TODO: replace this with real user_id
                :name => file.original_filename,
                :filename => file,
                :group_id=>group_id
                }

        image = Image.new(image_params)
        image.tag_list = params['tags']
        if(image.save)
          @images << image #TODO: currently unused. Consider removing
        end
      end

      flash[:notice] = "#{@images.size} image(s) saved successfully"
      redirect_to :controller => :groups, :action => 'show', :id => group_id
  end

  def edit
    @image = Image.find(params[:id])
  end

  def update
    @image = Image.find(params[:id])
    if @image.update_attributes(params[:image])
      flash[:notice] = 'Image was successfully updated.'
      redirect_to :action => 'show', :id => @image
    else
      render :action => 'edit'
    end
  end

  def update_ajax
#    puts "Updating by ajax #{params[:field_name]}"
#    puts params.inspect
    @image = Image.find(params[:id], :include => :tags)
    eval("@image.#{params[:field_name]} = params[:value]")
    if (!@image.valid?)
      errors = @image.errors.on(params[:field_name])
      if errors.type == Array
        flash[:error] = errors.map{|e| params[:field_name]+' '+ e+'.'}.join('<br />')
      else
        flash[:error] = params[:field_name] + ' ' + errors
      end
      @image.reload
    else
      @image.save
    end
    @new_value = eval("@image.#{params[:field_name]}")
    render :layout => 'ajax'
  end

  def tag
    if (not params[:selected_ids]) || (params[:selected_ids] == nil)
      raise ArgumentError, "Trying to tag without giving image ids."
    else
      render :layout => 'dialog'
    end
  end

  def update_tag
    puts params.inspect
    if (not params[:selected_ids]) || (params[:selected_ids] == nil)
      raise ArgumentError, "Trying to tag without giving image ids."
    else
      if (not params[:tag_names])
        flash[:error] = 'Please enter some tags (comma separated)'
      else
        params[:selected_ids].split(',').each do |image_id|
          if (an_image = Image.find(image_id))
            an_image.tag_list = an_image.tag_list + ','+  params[:tag_names]
            if (not an_image.save())
              flash[:error] = 'Error changing tags for image \##{image_id}'
              break
            end
          else
            raise ArgumentError, "Trying to tag non-existed image: id #{image_id}"
          end
        end
      end
    end
    flash[:notice] = 'Image tags updated successfully'
    render :layout => 'dialog'
  end

  def destroy
  #  File.delete("#{RAILS_ROOT}/media/#{@filename}") if File.exist?("#{RAILS_ROOT}/media/#{@filename}")
    @image =Image.find(params[:id])
    #TODO: rewrite image deletion
    #Image.find(params[:id]).destroy
    if(@image.destroy)
      flash[:notice] = "Image #{@image.name} has been deleted"
    else
      flash[:error] = "Could not delete image"
    end

    # redirect_to :action => 'list'
    render :layout => 'ajax'
  end
end
